package com.atguigu.web;

import com.atguigu.pojo.Cart;
import com.atguigu.pojo.User;
import com.atguigu.service.OrderService;
import com.atguigu.service.impl.OrderServiceImp;
import com.atguigu.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 徐州城
 * @version 1.0
 */
public class OrderServlet extends BaseServlet{
    private OrderService orderService = new OrderServiceImp();

    //生成订单和订单项
    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、先获取Cart购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        //2、获取userId
        User loginUser = (User) req.getSession().getAttribute("user");

        //loginUser == null说明，还没有登陆，请求转发回登陆界面
        if (loginUser == null){
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else {
            //已经登陆，可以从域 中拿去数据
            Integer userId = loginUser.getId();
            //2、调用OrderService.createOrder(Cart,userId); 生成订单和订单项
            String orderId = orderService.createOrder(cart, userId);

            //保存到Session域当中
            req.getSession().setAttribute("orderId",orderId);
            //请求转发到 /pages/cart/checkout.jsp
            //req.getRequestDispatcher("/pages/cart/checkout.jsp").forward(req,resp); //会出现重复提交bug

            resp.sendRedirect(req.getContextPath() + "/pages/cart/checkout.jsp");
        }

    }
}
